﻿using QDasTransfer.Transducer;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;

namespace QDasTransfer.Classes
{
    public class ParamaterData
    {
        public string filename = ".\\config.xml";

        public static Encoding[] Encodings = {
            Encoding.Default,
            Encoding.ASCII,
            Encoding.BigEndianUnicode,
            Encoding.Unicode,
            Encoding.UTF32,
            Encoding.UTF8,
            Encoding.UTF7};

        /*******************************************************
		 *  User Interface 
		 ********************************************************/
        public List<ListViewData> InputListViewWidth = new List<ListViewData>();

        /// <summary>
        /// How to process source file: 0.move; 1.no operation. 2. delete. 3. by program.
        /// </summary>
        public int ProcessSourceFileType = 0;


        /*******************************************************
		 *  Input setups
		 ********************************************************/
        public List<ConvertTask> InputPaths = new List<ConvertTask>();   
        public string OutputFolder = @"C:\QDas\Output";
        public string TempFolder = @"C:\QDas\Temp";
        public string FolderForSuccessed = @"C:\QDas\Backups\Success";
        public string FolderForFailed = @"C:\QDas\Backups\Failed"; 

        /*******************************************************
         * Output setups
         ********************************************************/

        /*******************************************************
		 *  System parameters
		 ********************************************************/
        /// <summary>
        ///  Determine how to deal with files with the same name as the output file. 
        ///  0: override;  
        ///  1: reanme by adding time tick, such as 1_20120516183025.dfq
        ///  2: add increased index by 1.
        ///  3: merge files.
        /// </summary>
        public int DealSameOutputFileNameType = 0;
        /// <summary>
        /// How many levels kept for output folder.
        /// </summary>
        public int KeepOutFolderStructLevel = 0;
        /// <summary>
        /// How to deal with backup struct. 
        /// 0: do not keep structure; 
        /// 1: keep all structure; 
        /// otherwise: undefined.
        /// </summary>
        public int KeepBackupFolderStructType = 0;
        /// <summary>
        /// How many levels kept for backup folder.
        /// </summary>
        public int KeepBackupFolderStructLevel = 0;  
        /// <summary>
        /// 打开文件时，选择的默认索引序号同，如“txt文件|*.txt|所有文件|*.*”
        /// 注意：此值下标从1开始，所以默认为1。
        /// </summary>
        public int FilterIndex = 1;  
        /// <summary>
        /// 是否遍历子目录。
        /// </summary>
        public bool TraverseSubfolders = false;
        /// <summary>
        /// 是否使用自定义格式
        /// </summary>
        public string CostomizedDateTimeFormat = ""; 
        /// <summary>
        /// 扩展名列表
        /// </summary>
        public List<string> extentions = new List<string>(); 
        /// <summary>
        /// 编码的ID。
        /// </summary>
        public int EncodingID = 0;

        /******************** Auto Transduce **********************/
        public DateTime StartTime = DateTime.Now;
        public DateTime EndTime = DateTime.Now;
        public int CircleValue = 1;
        public int CircleUnit = 60;

        /// <summary>
        /// whether turns on the autotrans. Note: 'SupportAutoTransducer' should be true. 
        /// </summary>
        public bool AutoTransducerAvaliable = false;
        /// <summary>
        /// Whether this transducer supports automatic transduction.
        /// </summary>
        public bool SupportAutoTransducer = true;


        /// <summary>
        /// 根据给定的XML文件初始化一个ParamaterData对象，如果失败，返回空对象，但是filename的值为infile。
        /// </summary>
        /// <param name="infile"></param>
        /// <returns></returns>
        public static ParamaterData Load(string infile)
        {
            ParamaterData pd;
            if (File.Exists(infile))
            {
                try
                {
                    XmlDocument doc = new XmlDocument();
                    doc.Load(infile);
                    pd = WindGoes6.Data.Serializer.GetObject<ParamaterData>(doc);
                    pd.filename = infile;
                    return pd;
                }
                catch { }
            }
            pd = new ParamaterData
            {
                filename = infile
            };
            return pd;
        }

        public ParamaterData()
        {
            Initialize();
        }
 

        public void Initialize()
        {
            string qds = "C:\\QDAS";
            OutputFolder = qds + "\\Output";
            TempFolder = qds + "\\Temp";
            FolderForSuccessed = qds + "\\Backups\\Success";
            FolderForFailed = qds + "\\Backups\\Failed";
            KeepOutFolderStructLevel = 0;
            ProcessSourceFileType = 1; 
            StartTime = new DateTime(2000, 1, 1, 0, 0, 0);
            EndTime = new DateTime(2000, 1, 1, 23, 59, 59);
            CircleValue = 10;
            CircleUnit = 1; 
            TraverseSubfolders = false;
            extentions = new List<string>();
        }

        /// <summary>
        /// 根据输入文件路径和要保存的层数，返回输出路径。
        /// </summary>
        /// <param name="infile"></param>
        /// <returns></returns>
        public string GetOutDirectory(string infile)
        {
            return Path.Combine(OutputFolder, FileHelper.GetLastDirectory(infile, KeepOutFolderStructLevel));
        }

        public ParamaterData Clone()
        {
            string xml = WindGoes6.Data.Serializer.GetXmlDoc(this).InnerXml;
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xml);
            ParamaterData sp = WindGoes6.Data.Serializer.GetObject<ParamaterData>(doc);
            sp.filename = this.filename;
            return sp;
        }


        public int getCircleInterval()
        {
            return CircleValue * (int)Math.Pow(60, CircleUnit);
        }

        /// <summary>
        /// 添加可以被访问的扩展名，名称长度不限，加不加点都行。会自动转换为小写。
        /// </summary>
        /// <param name="name"></param>
        public void AddExt(string name)
        {
            if (string.IsNullOrEmpty(name))
                return;

            if (name[0] != '.')
                name = "." + name;

            extentions.Add(name.ToLower());
        }

        /// <summary>
        /// 验证一个文件全路径是否是合法的文件类型。
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public bool ValidateExtention(string path)
        {
            string ext = Path.GetExtension(path).ToLower();
            for (int i = 0; i < extentions.Count; i++)
            {
                if (extentions[i].Contains(ext))
                {
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 获得可用的扩展名。这个是对话框所使用的。
        /// </summary>
        /// <returns></returns>
        public string GetExtFilter()
        {
            StringBuilder builder = new StringBuilder();

            if (extentions.Count == 0)
                return "所有文件|*.*";

            builder.Append("待转换的数据文件|");
            for (int i = 0; i < extentions.Count; i++)
                builder.Append("*" + extentions[i] + ";");
            builder.Remove(builder.Length - 1, 1);
            builder.Append("|所有文件|*.*");

            return builder.ToString();
        }

        /// <summary>
        /// Load from XML data.
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static ParamaterData LoadParamater(string path)
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(path);
                return WindGoes6.Data.Serializer.GetObject<ParamaterData>(doc);
            }
            catch { }
            return new ParamaterData();
        }

        public void Save(string path)
        {
            filename = path;
            Save();
        }


        public void Save()
        {
            if (File.Exists(filename))
                File.Delete(filename);
            WindGoes6.Data.Serializer.GetXmlDoc(this).Save(filename);
        }

        public string GetOutfileName(string infile)
        {
            string keptfolder = FileHelper.GetLastDirectory(infile, KeepOutFolderStructLevel);
            return string.Format("{0}\\{1}.dfq", Path.Combine(OutputFolder, keptfolder), Path.GetFileNameWithoutExtension(infile));
        }
    }
}
